package com.rew.canteenbox.activities;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.rew.canteenbox.R;
import com.rew.canteenbox.bases.AppData;
import com.rew.canteenbox.bases.SlideActivity;
import com.rew.canteenbox.fragments.FCounter;
import com.rew.canteenbox.functions.StatusBarUtils;
import com.rew.canteenbox.models.Dishes;
import com.rew.canteenbox.models.Orders;
import com.rew.canteenbox.models.Result;

import java.lang.reflect.Type;
import java.util.List;

import static com.nineoldandroids.view.ViewPropertyAnimator.animate;
import static com.rew.canteenbox.http.Api.URL_ESTU_DISH_DETAIL;

/**
 * 食品详情.
 * <p>
 * Created by HuiWen Ren on 2016/10/18.
 */

public class InfoActivity extends SlideActivity implements View.OnClickListener {

    // 逻辑变量声明.
    private String dishes_name;//菜品名称.
    private Button backBtn;    //回退按钮.
    private AppData appData;
    private Dishes dishes;

    // 布局变量声明.
    private TextView nameText;  //菜品名称.
    private TextView infoText;  //菜品详情.
    private ImageView picImg;   //菜品图片.

    private FCounter fCounter;

    private android.view.animation.Animation animation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置状态栏颜色
        StatusBarUtils.setWindowStatusBarColor(InfoActivity.this, R.color.colorPrimaryDark);

        appData = (AppData) getApplication();

        Intent intent = getIntent();
        // 菜品名称传递.
        dishes_name = intent.getStringExtra("dishes_name");
        /*
            动画加载.
            注意此处制定的是同一时刻的出入动画.
            而非该活动的自身出入动画.
         */
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        viewInit();

        /*
            动态加载布局加载.
         */

        // 信息初始化(测试).
        dishes = new Dishes();

        get(URL_ESTU_DISH_DETAIL + "test-dish");
//        Toast.makeText(InfoActivity.this,dishes.getName(),Toast.LENGTH_SHORT).show();

         dishes = finDish(dishes_name);
         fCounter = new FCounter();
         fCounter.setDish(dishes);

         FragmentManager fm = getFragmentManager();
         // 开启Fragment事务
         FragmentTransaction transaction = fm.beginTransaction();
         transaction.replace(R.id.info_counter, fCounter);
         transaction.commit();

         // 数据库信息加载(正式).


         // 更新布局.
         nameText.setText(dishes_name);
         infoText.setText(dishes.getDishesInfo());
         picImg.setImageResource(dishes.getPicId());
    }

    @Override
    public void onDataOK(String url, String data) {
        Log.d("InfoActivity","onDataOK");
        Toast.makeText(InfoActivity.this,"onDataOK",Toast.LENGTH_SHORT).show();
        if(url.equals(URL_ESTU_DISH_DETAIL + "test-dish")){
            Log.d("InfoActivity","urlEQUAL");
            Gson gson = new Gson();
            Type jsonType = new TypeToken<Result<Dishes>>() {
            }.getType();
            Result<Dishes> result = gson.fromJson(data, jsonType);
            Dishes dishes = result.getBean();
            // Debug
            Log.d("InfoActivity","get_dishes name:"+dishes.getDishName());
            Log.d("InfoActivity","get_dishes num:"+dishes.getDishNum());
            Log.d("InfoActivity","get_dishes price:"+dishes.getDishPrice());
       } else {
            Log.d("InfoActivity","urlERROR");
            Toast.makeText(InfoActivity.this,"urlERROR",Toast.LENGTH_SHORT).show();
        }
    }

    /*
        启动接口.
     */
    public static void actionStart(Context context, String dishes_name) {
        Intent intent = new Intent(context, InfoActivity.class);
        intent.putExtra("dishes_name", dishes_name);
        context.startActivity(intent);
    }

    private void viewInit(){
        animation = AnimationUtils.loadAnimation(this, R.anim.add_score_anim);

        setContentView(R.layout.activity_info);

        // 回退按钮设定.
        backBtn = (Button) findViewById(R.id.dishes_info_back);
        backBtn.setOnClickListener(this);

        LinearLayout ll_info_to_buy = (LinearLayout) findViewById(R.id.ll_info_to_buy);
        ll_info_to_buy.setOnClickListener(this);
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.info_activity);
        relativeLayout.setOnTouchListener(this);

        nameText = (TextView) findViewById(R.id.dishes_info_name);
        infoText = (TextView) findViewById(R.id.info_body);
        picImg = (ImageView) findViewById(R.id.dishes_info_img);
    }

    /*
        点击事件.
     */
    @Override
public void onClick(View v) {
        switch (v.getId()) {
            // 回退按钮点击.
            case R.id.dishes_info_back:
                finish();
                break;
            case R.id.ll_info_to_buy:
                OrderDialog();
                //Toast.makeText(InfoActivity.this, "InfoToBuyHere", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    private void OrderDialog(){
        List<Orders> ordersList = appData.getOrdersList();
        String[] orderString = new String[ordersList.size()+1];
        orderString[0] = "当前已有订单为：";
        for(int i = 0;i<ordersList.size();i++){
            Orders orders = ordersList.get(i);
            orderString[i+1] ="\t"+orders.getDishes().getDishName()
                    + "\t\t" + Integer.toString(orders.getNum());
        } if(ordersList.size() == 0) orderString[0] = "当前无订单信息";
        new AlertDialog.Builder(this).setTitle("订单列表").setItems(
                orderString, null).setNegativeButton(
                "确定", null).show();
    }

    /*
        重载 向右滑动 为 回退.
        并更改主活动动画为 入左出右.
    */
    @Override
    public void right() {
        MainActivity.inStyle = R.anim.in_from_left;
        MainActivity.outStyle = R.anim.out_from_right;
        MainActivity.actionStart(InfoActivity.this);
        super.finish();
    }

    /*
        重载手机 回退命令 为 回退.
        并更改主活动动画为 入左出右.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == android.view.KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            MainActivity.inStyle = R.anim.in_from_left;
            MainActivity.outStyle = R.anim.out_from_right;
            MainActivity.actionStart(InfoActivity.this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Dishes finDish(String dishes_name){
        List<Dishes> dishesList = appData.getDishesList();
        for (Dishes aDishesList : dishesList) {
            if (aDishesList.getDishName().equals(dishes_name)) {
                return aDishesList;
            }
        }
        return null;
    }


    private void animateClickView(final View v, final ClickAnimation callback) {
        float factor = 2;
        animate(v).scaleX(factor).scaleY(factor).alpha(0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(com.nineoldandroids.animation.Animator animation) {
                ViewHelper.setScaleX(v, 1);
                ViewHelper.setScaleY(v, 1);
                ViewHelper.setAlpha(v, 1);
                if (callback != null) {
                    callback.onClick(v);
                }
                super.onAnimationEnd(animation);
            }
        });
    }

    public interface ClickAnimation {
        public void onClick(View v);
    }

}
